﻿using HP.HPTRIM.SDK;
using ServiceStack.Configuration;
using ServiceStack.Logging;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
using System;
using System.IO;

namespace DocuSignPlugin
{
    public class TrimHelper
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(TrimHelper));

        private Database _database;

        private TrimHelper() { }

        public TrimHelper(Database database, AppSettings appSettings)
        {
            _database = database;
        }

        public bool checkIn(long id, string filename)
        {
            bool status = false;

            try
            {
                Record record = new Record(_database, id);
                record.SetDocument(new InputDocument(filename), true, false, "Checked in from Signing.");
                record.Save();
                File.Delete(filename);

                status = true;

            }
            catch (Exception ex)
            {
                _log.Debug("[ERROR - CheckinCheckout] checkIn: " + ex.Message);
                throw;
                //  GoToErrorPage(ex.Message);

            }

            return status;
        }

        public string checkOut(long id)
        {

            try
            {
                Record record = new Record(_database, id);

                if (!record.IsDocumentInClientCache)
                {
                    record.LoadDocumentIntoClientCache();
                }

                record.GetDocument(null, true, "checkout for DocuSign", null);


                return record.DocumentPathInClientCache;


            }
            catch (Exception ex)
            {
                _log.Debug("[ERROR - CheckinCheckout] checkOut: " + ex.Message);
                throw;
            }
        }

        public string GetUserEmailAddress()
        {

            try
            {
                //emailAddress = _database.CurrentUser.EmailAddress;
                //return _database.CurrentUser.FullFormattedName + "~" + _database.CurrentUser.EmailAddress;
                return _database.CurrentUser.EmailAddress;

            }
            catch (Exception ex)
            {
                _log.Debug("[ERROR - CheckinCheckout] GetUserEmailAddress: " + ex.Message);
                //    GoToErrorPage(ex.Message);
                return "";
            }
        }

        public string GetUserName()
        {

            try
            {
                //emailAddress = _database.CurrentUser.EmailAddress;
                //return _database.CurrentUser.FullFormattedName + "~" + _database.CurrentUser.EmailAddress;
                return _database.CurrentUser.FullFormattedName;

            }
            catch (Exception ex)
            {
                _log.Debug("[ERROR - CheckinCheckout] GetUserFullFormattedName: " + ex.Message);
                //    GoToErrorPage(ex.Message);
                return "";
            }
        }


        public string getDocName(long id)
        {
            string docName = null;

            Record record = new Record(_database, id);
            docName = record.SuggestedFileName;

            return docName;
        }



        private const string USER_CREDENTIALS_KEY = "docusign.user.credentials";
        internal void setUserCredentials(LoginDetails credentials, IHttpResponse response)
        {
            response.Cookies.AddPermanentCookie("docusign.auth", credentials.AccessToken, true);

            string json = new LoginDetails() { AccountId = credentials.AccountId, BaseUrl = credentials.BaseUrl }.ToJson();
            _database.SetUserAppConfig(USER_CREDENTIALS_KEY, json);
        }

        internal LoginDetails getUserCredentials(IHttpRequest request)
        {
            string credentials = _database.GetUserAppConfig(USER_CREDENTIALS_KEY);

            LoginDetails loginDetails = new LoginDetails();

            if (!string.IsNullOrEmpty(credentials))
            {

                try
                {
                    loginDetails = credentials.FromJson<LoginDetails>();
                }
                catch
                {
                    // if the value in UserAppconfig is corrupt we will have to re-fetch it later.
                }
            }

            if (request.Cookies.ContainsKey("docusign.auth"))
            {
                loginDetails.AccessToken = request.Cookies["docusign.auth"].Value;
            }
            return loginDetails;
        }

        internal void UndoCheckout(long uri)
        {
            Record record = new Record(_database, uri);

            if (record.IsCheckedOut)
            {
                record.UndoCheckout("DocuSign, signing abandoned.");
                record.Save();
            }
        }
    }
}
